import { Menu, Icon } from 'antd';
import * as React from 'react';
import menu from '../../config/menu';


const { SubMenu } = Menu;

interface Props{
  history?:any
}
class IMnenu extends React.Component<Props> {
  // submenu keys of first level
  rootSubmenuKeys: string[] = [];
  state = {
    openKeys: ['/'],
    selectedKeys:["/user/list"]
  };

  componentDidMount() {
   let url:string = window.location.href;
   url = url.substring(url.lastIndexOf('#') + 1, url.length); 
   let openKey:string = url.substring(0, url.lastIndexOf('/'),);
   this.setState({
    selectedKeys:[url],
    openKeys:[openKey],
   })
  }

  onOpenChange = (openKeys: []) => {
    menu.forEach((item: any) => {
      this.rootSubmenuKeys.push(item.path);
    })
    const latestOpenKey = openKeys.find((key: string) => this.state.openKeys.indexOf(key) === -1);
    if (this.rootSubmenuKeys.indexOf(latestOpenKey) === -1) {
      this.setState({ openKeys });
    } else {
      this.setState({
        openKeys: latestOpenKey ? [latestOpenKey] : [],
      });
    }
  };
  goMenu=(opt:any) =>{
    this.setState({
      selectedKeys:[opt.key],
     })
    this.props.history.push(opt.key);
  };

  render() {
    return (
      <Menu
        mode="inline"
        openKeys={this.state.openKeys}
        onOpenChange={this.onOpenChange}
        onClick={this.goMenu}
        selectedKeys={this.state.selectedKeys}
      >
        {
          menu.map((item: any, i: number) => {
            if (item.children) {
              return <SubMenu
                key={item.path}
                title={
                  <span>
                    <Icon type={item.iconType} />
                    <span>{item.name}</span>
                  </span>
                }
              >
                {
                  item.children.map((item: any) => {
                    return <Menu.Item key={item.path}>{item.name}</Menu.Item>
                  })
                }
              </SubMenu>
            } else {
              return <Menu.Item key={item.path}>
               <Icon type={item.iconType} />
               <span>{item.name}</span>
              </Menu.Item>
            
            }

          })

        }
      </Menu>
    );
  }
}
export default IMnenu;